package it.antonioduca.citt;

import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

public class CallListener extends PhoneStateListener {

	private final String TAG = "Citt";

	private AudioManager audioManager;
	private SensorManager sensorManager;
	private Sensor orientation;
	private	FlipListener flipListener;
	private int actualRingerMode;
	private boolean ringing = false;
	
	public CallListener(AudioManager am, SensorManager sm) {
		super();
		audioManager = am;
		sensorManager = sm;
		
		// TODO: Sensor.TYPE_ORIENTATION is deprecated!
        orientation = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
	}
	
	@Override
	public void onCallStateChanged(int state, String incomingNumber) {
	    if(state == TelephonyManager.CALL_STATE_RINGING) {
			Log.i(TAG, "RINGING!");
	    	actualRingerMode = audioManager.getRingerMode();
	    	flipListener = new FlipListener(audioManager);
	        sensorManager.registerListener(flipListener, orientation, SensorManager.SENSOR_DELAY_NORMAL);
	        ringing = true;
	    } else if(ringing && state == TelephonyManager.CALL_STATE_IDLE) {
			Log.i(TAG, "IDLE...");
	    	sensorManager.unregisterListener(flipListener);
	    	audioManager.setRingerMode(actualRingerMode);
	    	ringing = false;
	    }
	}
}
